package com.example.it_com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.it_com.common.Result;
import com.example.it_com.entity.Blog;
import com.example.it_com.entity.User;
import com.example.it_com.mapper.UserMapper;
import com.example.it_com.service.BlogService;
import com.example.it_com.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogService blogService;


    //用户登录
    @PostMapping("/login")
    public Result<User> login(String username, String password, Integer permissionType) {
        log.info(username);
        log.info(password);

        //我的代码
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username)
                .eq(User::getPassWord, password);
        User user = userService.getOne(queryWrapper);


        if (user == null) {
            return Result.error(null, "用户名或密码不存在");
        }
        //状态 status 0正常 1封禁
        if (user.getStatus() == 1) {
            return Result.error(null, "用户已封禁");
        }
        //判断permissionType 判断是否为管理员还是普通用户
        if (user.getPermissionType() == 1) {
            return Result.success(user, "管理员登录成功");
        }
        return Result.success(user, "用户登录成功");
    }


    //用户注册
    @PostMapping("/register")
    public Result<String> register(String username, String password, String email) {
        log.info(username);
        log.info(password);
        log.info(email);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User one = userService.getOne(queryWrapper);

        User user = new User();
        user.setEmail(email);
        user.setUserName(username);
        user.setPassWord(password);
        user.setRegistrationDate(LocalDateTime.now());
        user.setImg("https://tse4-mm.cn.bing.net/th/id/OIP-C.UyaBji0AU_6M3VDA2F1RvgAAAA?rs=1&pid=ImgDetMain");


        // 是否已有该用户
        if (one == null) {
            // 验证码是否正确
            boolean save = userService.save(user);
            // 是否插入成功
            if (save) {
                return Result.success("", "注册成功");
            } else {
                return Result.error("", "注册失败");
            }
        }

        return Result.error("", "用户名已经存在");


    }

    //用户修改密码
    @PostMapping("/changepasswd")
    public Result<String> changeUserPasswd(Integer userId, String newPasswd, String oldPasswd) {
        log.info(userId.toString());
        log.info("password:" + newPasswd);
        //用于查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        //用于更新
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        //根据id查询用户
        queryWrapper.eq(User::getUserId, userId);
        updateWrapper.eq(User::getUserId, userId);
        User one = userService.getOne(queryWrapper);
        log.info(userId.toString());


        if (one.getPassWord().equals(oldPasswd)) {
            //成功修改
            one.setPassWord(newPasswd);
            userMapper.update(one, updateWrapper);
            return Result.success("", "更改用户密码成功");
        } else {
            //原密码错误
            return Result.success("", "原密码错误");
        }

    }

    //用户个人中心(基本信息)
    @PostMapping("/personal")
    public Result<User> personal(Integer userId) {
        log.info(userId.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(queryWrapper);


        //返回用户基本信息
        return Result.success(user, "返回成功");
    }


    //用户个人中心(博客信息)
    @GetMapping("/personal/blog")
    public Result<List<Blog>> personalBlog(Integer userId) {
        log.info(userId.toString());

        LambdaQueryWrapper<Blog> blogWrapper = new LambdaQueryWrapper<>();
        blogWrapper.eq(Blog::getUserId, userId);
        List<Blog> blogs = blogService.list(blogWrapper);

        // 返回用户帖子列表
        return Result.success(blogs, "返回成功");
    }

    //用户头像上传（上传uml）
    @PostMapping("/uploadimg")
    public Result<User> uploadimg(Integer userId, String img) {
        log.info(userId.toString());
        log.info(img);

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId);
        updateWrapper.set(User::getImg, img);
        userService.update(updateWrapper);
        User user = userService.getOne(updateWrapper);

        return Result.success(user, "上传成功");
    }

    //修改用户名
    @PostMapping("/changeusername")
    public Result<User> changeUserName(Integer userId, String newUserName) {
        log.info(userId.toString());
        log.info(newUserName);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId);
        updateWrapper.set(User::getUserName, newUserName);
        userService.update(updateWrapper);
        User user = userService.getOne(updateWrapper);


        return Result.success(user, "更改用户名成功");
    }

    //修改用户邮箱
    @PostMapping("/changeemail")
    public Result<User> changeEmail(Integer userId, String newEmail) {
        log.info(userId.toString());
        log.info(newEmail);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId);
        updateWrapper.set(User::getEmail, newEmail);
        userService.update(updateWrapper);
        User user = userService.getOne(updateWrapper);
        return Result.success(user, "更改用户邮箱成功");
    }

    //头像上传（上传本地图片）
    @PostMapping("/uploadrealimg")
    public String uploadrealimg(MultipartFile file, Integer userId) {
        // 检查上传的文件是否为空
        if (file.isEmpty()) {
            return "图片为空";
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 使用当前时间戳作为文件名前缀，确保文件名唯一性
        String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        // 断言原始文件名不为空（如果为空会抛出异常）
        assert originalFilename != null;

        // 获取文件扩展名（假设文件名包含点号分隔的扩展名）
        String fileNameSuffix = "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        // 组合新的文件名：时间戳 + 原始文件扩展名
        String fileName = fileNamePrefix + fileNameSuffix;

        // 构建保存图片的目标路径
        String path = "E:/基础环境与示例代码/it-software/src/main/resources/img/" + fileName;

        try {
            // 将上传的文件保存到指定路径
            file.transferTo(new File(path));

            log.info("图片保存路径: {}", path);

            // 数据库中保存图片路径
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUserId, userId);
            updateWrapper.set(User::getImg, "http://localhost:8080/" + fileName); // 注意这里的路径是相对路径
            userService.update(updateWrapper);

            User user = userService.getOne(updateWrapper);
            log.info(user.toString());

            // 构建返回给前端的相对路径，方便前端引用
            String relativePath = "/img/" + fileName;

            // 返回处理后的路径字符串
            return relativePath;
        } catch (IOException e) {
            // 捕获并打印IO异常信息
            e.printStackTrace();
            return "图片上传失败";
        }
    }

}
